package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.*;
import com.cskaoyan.bean.vo.WxCartCheckoutVo;
import com.cskaoyan.bean.vo.WxCartIndexVo;
import com.cskaoyan.bean.vo.wxcart.index.CartListBean;
import com.cskaoyan.bean.vo.wxcart.index.CartTotalBean;
import com.cskaoyan.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @description:
 * @author: Tao
 * @time: 2022/12/31 23:50
 */
@Service
public class WxCartServiceImpl implements WxCartService {
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketAddressMapper addressMapper;

    /**
     * 执行查找购物车中商品数量的操作
     *
     * @return
     */
    @Override
    public int getGoodsCount() {
        MarketCartExample example1 = new MarketCartExample();
        //条件查询
        MarketCartExample.Criteria criteria = example1.createCriteria();
        //获取当前用户的id
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        Integer userId = principal.getId();
        criteria.andUserIdEqualTo(userId);
        List<MarketCart> marketCarts = cartMapper.selectByExample(example1);
        //计算购物车中所有商品的数量
        int sum = 0;
        for (MarketCart marketCart : marketCarts) {
            Short number = marketCart.getNumber();
            sum += number;
        }
        return sum;
    }

    /**
     * 执行加入购物车的操作
     *
     * @param wxCartAddBo
     */
    @Override
    public void addCart(WxCartAddBo wxCartAddBo) {
        Integer goodsId = wxCartAddBo.getGoodsId();
        Short number = wxCartAddBo.getNumber();
        Integer productId = wxCartAddBo.getProductId();
        //获取商品信息
        MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
        //给购物车赋值
        MarketCart marketCart = new MarketCart();
        //获取当前用户的id
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        Integer userId = principal.getId();
        marketCart.setUserId(userId);
        marketCart.setGoodsId(goodsId);
        marketCart.setGoodsSn(goods.getGoodsSn());
        marketCart.setGoodsName(goods.getName());
        marketCart.setProductId(productId);
        marketCart.setPrice(goods.getRetailPrice());
        marketCart.setNumber(number);

        //给购物车的Specifications属性赋值
        //实例化对象
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        //增加条件查询
        MarketGoodsSpecificationExample.Criteria criteria = marketGoodsSpecificationExample.createCriteria();
        criteria.andGoodsIdEqualTo(goods.getId());
        //查找此商品的所有的Specifications信息
        List<MarketGoodsSpecification> marketGoodsSpecifications = specificationMapper.selectByExample(marketGoodsSpecificationExample);
        //存放最终的Specifications信息  格式 Specifications1-Specifications2-Specifications3
        String temp = "";
        int size = marketGoodsSpecifications.size();
        //仅有一个规格
        if (size <= 1) {
            for (MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecifications) {
                temp = temp + marketGoodsSpecification.getValue();
            }
        } else {
            //有多个规格用-分隔
            int num = 1;
            for (MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecifications) {
                if (num <= size - 1) {
                    //不是最后一个规格
                    temp = temp + marketGoodsSpecification.getValue() + "-";
                } else {
                    //是最后一个规格
                    temp = temp + marketGoodsSpecification.getValue();
                }
                num++;
            }
        }
        marketCart.setSpecifications(temp);
        marketCart.setChecked(true);
        marketCart.setPicUrl(goods.getPicUrl());
        marketCart.setAddTime(new Date());
        marketCart.setUpdateTime(new Date());
        marketCart.setDeleted(false);
        //执行插入
        cartMapper.insertSelective(marketCart);

    }

    /**
     * 实现查找购物车商品的功能
     *
     * @return 用户的购物车
     */
    @Override
    public WxCartIndexVo getCartIndex() {
        //将当前用户购物车中所有商品查出来
        //获取当前用户的id
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        Integer userId = principal.getId();
        //实例化对象
        MarketCartExample example = new MarketCartExample();
        //增加条件查询
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        // 查询逻辑存在,表中deleted字段值为1是删除状态
        criteria.andDeletedEqualTo(false);
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        //此时marketCarts中的Specifications信息  格式 Specifications1-Specifications2-Specifications3

        //先封装cartList
        ArrayList<CartListBean> cartList = new ArrayList<>();
        for (MarketCart marketCart : marketCarts) {
            //获得Specifications的字符集合
            List<String> list = getStringsArray(marketCart);
            //此时list含有所有的Specifications信息
            //获取封装之后的购物车Vo
            CartListBean cartListBean = getCartList(marketCart, list);
            cartList.add(cartListBean);
        }

        //再封装CartTotal
        //先计算出所有商品的数量以及价格
        short allGoodsNum = 0;
        Double allgoodsPrice = 0.0;

        //再计算出所有商品的数量以及价格
        short checkedGoodsNum = 0;
        Double checkedgoodsPrice = 0.0;

        for (MarketCart marketCart : marketCarts) {
            //先计算出所有商品的数量以及价格
            allGoodsNum += marketCart.getNumber();
            BigDecimal price = marketCart.getPrice();
            String s = price.toString();
            Double dprice = Double.valueOf(s);
            //获取此条购物车信息中商品的数量
            Short allGoodsNumber = marketCart.getNumber();
            allgoodsPrice = allgoodsPrice + (dprice * allGoodsNumber);

            //再计算出已经选择商品的数量以及价格
            if (marketCart.getChecked()) {
                //此时已经选择了
                checkedGoodsNum += marketCart.getNumber();
                BigDecimal checkedprice = marketCart.getPrice();
                String checkeds = checkedprice.toString();
                Double checkedprices = Double.valueOf(checkeds);
                Short checkedNumber = marketCart.getNumber();
                checkedgoodsPrice = checkedgoodsPrice + (checkedprices * checkedNumber);
            }
        }

        WxCartIndexVo wxCartIndexVo = new WxCartIndexVo();
        CartTotalBean cartTotalBean = new CartTotalBean((int) allGoodsNum, (int) checkedGoodsNum, allgoodsPrice, checkedgoodsPrice);
        wxCartIndexVo.setCartTotal(cartTotalBean);
        wxCartIndexVo.setCartList(cartList);

        return wxCartIndexVo;
    }

    /**
     * 获取封装之后的购物车Vo
     *
     * @param marketCart
     * @param list
     * @return
     */
    public static CartListBean getCartList(MarketCart marketCart, List<String> list) {
        return new CartListBean(marketCart.getId(), marketCart.getUserId(), marketCart.getGoodsId(),
                marketCart.getGoodsSn(), marketCart.getGoodsName(), marketCart.getProductId(), marketCart.getPrice(), marketCart.getNumber(),
                list, marketCart.getChecked(), marketCart.getPicUrl(), marketCart.getAddTime(), marketCart.getUpdateTime(),
                marketCart.getDeleted());
    }

    /**
     * 将数据库中一条购物车信息的Specifications字符串->字符集合
     *
     * @param marketCart
     * @return
     */
    public List<String> getStringsArray(MarketCart marketCart) {
        //获取marketCarts中的Specifications信息
        String specifications = marketCart.getSpecifications();
        String[] split = specifications.split("-");
        ArrayList<String> list = new ArrayList<>();
        //数组转化为list
        Collections.addAll(list, split);
        return list;
    }

    /**
     * 购物车中的选择功能
     *
     * @param checkedBo
     * @return
     */
    @Override
    public WxCartIndexVo checked(WxCartCheckedBo checkedBo) {
        //获取当前用户的id
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        Integer userId = principal.getId();
        //获取所有要修改选择的商品规格
        List<Integer> productIds = checkedBo.getProductIds();
        //循环修改购物车中商品的选中状态
        for (Integer productId : productIds) {
            //通过规格id找到商品的id
            MarketGoodsProduct marketGoodsProduct = productMapper.selectByPrimaryKey(productId);
            Integer goodsId = marketGoodsProduct.getGoodsId();
            //实例化对象
            MarketCartExample example = new MarketCartExample();
            //增加条件查询
            MarketCartExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andProductIdEqualTo(productId);
            criteria.andGoodsIdEqualTo(goodsId);
            //此时只有一条购物车记录
            List<MarketCart> marketCarts = cartMapper.selectByExample(example);
            Integer cartId = marketCarts.get(0).getId();
            Integer isChecked = checkedBo.getIsChecked();
            MarketCart marketCart = new MarketCart();
            marketCart.setId(cartId);
            if (isChecked == 1) {
                //要选择此购物车中的商品
                marketCart.setChecked(true);
            } else {
                marketCart.setChecked(false);
            }
            //修改
            cartMapper.updateByPrimaryKeySelective(marketCart);
        }

        //回显购物车现在的信息
        WxCartIndexVo cartIndex = getCartIndex();
        return cartIndex;
    }

    /**
     * 购物车的删除
     *
     * @param wxCartDeleteBo
     * @return
     */
    @Override
    public WxCartIndexVo delete(WxCartDeleteBo wxCartDeleteBo) {
        //获取当前用户的id
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        Integer userId = principal.getId();
        //获取购物车信息中要删除的所有规格id
        List<Integer> productIds = wxCartDeleteBo.getProductIds();
        //遍历一个个删除
        for (Integer productId : productIds) {
            //通过规格id找到商品的id
            MarketGoodsProduct marketGoodsProduct = productMapper.selectByPrimaryKey(productId);
            Integer goodsId = marketGoodsProduct.getGoodsId();
            //实例化对象
            MarketCartExample example = new MarketCartExample();
            //增加条件查询
            MarketCartExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andProductIdEqualTo(productId);
            criteria.andGoodsIdEqualTo(goodsId);
            //此时只有一条购物车记录
            List<MarketCart> marketCarts = cartMapper.selectByExample(example);
            MarketCart marketCart = marketCarts.get(0);
            //获得要删除的购物车记录id
            Integer id = marketCart.getId();
            // 获得 要删除的购物车记录的逻辑删除标志
            Boolean deleted = marketCart.getDeleted();
            // 通过id 更新 删除标记
            MarketCart marketCartDelete = new MarketCart();
            marketCartDelete.setId(id);
            // 删除标记取反
            marketCartDelete.setDeleted(!deleted);
            cartMapper.updateByPrimaryKeySelective(marketCartDelete);
        }
        //回显购物车的列表
        WxCartIndexVo cartIndex = getCartIndex();
        return cartIndex;
    }

    /**
     * 修改购物车记录功能
     *
     * @param cartUpdateBo
     */
    @Override
    public void update(WxCartUpdateBo cartUpdateBo) {
        //获取要修改的购物车信息
        Integer id = cartUpdateBo.getId();
        if (id != null) {
            //此时是在购物车修改操作
            //获取此购物车记录
            MarketCart marketCart = cartMapper.selectByPrimaryKey(id);
            //修改商品数量和商品的规格
            marketCart.setNumber(cartUpdateBo.getNumber());
            marketCart.setProductId(cartUpdateBo.getProductId());
            //修改数据库中购物车记录
            cartMapper.updateByPrimaryKeySelective(marketCart);
        } else {
            //此时是快速购买中修改购物车中商品数量的操作
            //获取当前用户的id
            Subject subject = SecurityUtils.getSubject();
            MarketUser principal = (MarketUser) subject.getPrincipal();
            Integer userId = principal.getId();
            //实例化对象
            MarketCartExample example = new MarketCartExample();
            //增加条件查询
            MarketCartExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andGoodsIdEqualTo(cartUpdateBo.getGoodsId());
            criteria.andProductIdEqualTo(cartUpdateBo.getProductId());
            List<MarketCart> marketCarts = cartMapper.selectByExample(example);
            //获取要修改的购物车信息
            MarketCart marketCart = marketCarts.get(0);
            //修改商品的数量(直接替换掉数据库中购物车规格数量)
            marketCart.setNumber(cartUpdateBo.getNumber());
            //对数据库修改
            cartMapper.updateByPrimaryKeySelective(marketCart);
        }

    }

    @Override
    public Integer fastAdd(WxCartFastAddBo wxCartFastAddBo) {
        //有二种情况第一种购物车中没有此商品则添加到购物车，第二种有此商品执行更改商品的数量
        //获取当前用户的id
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        Integer userId = principal.getId();
        //实例化对象
        MarketCartExample example = new MarketCartExample();
        //增加条件查询
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andGoodsIdEqualTo(wxCartFastAddBo.getGoodsId());
        criteria.andProductIdEqualTo(wxCartFastAddBo.getProductId());
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        if (marketCarts.size() == 0) {
            //此时是第一种购物车中没有此商品则添加到购物车
            WxCartAddBo wxCartAddBo = new WxCartAddBo(wxCartFastAddBo.getGoodsId(), wxCartFastAddBo.getNumber(), wxCartFastAddBo.getProductId());
            //加入购物车
            addCart(wxCartAddBo);
        } else {
            //此时是第二种有此商品执行更改商品的数量
            WxCartUpdateBo wxCartUpdateBo = new WxCartUpdateBo(wxCartFastAddBo.getProductId(), wxCartFastAddBo.getGoodsId(), wxCartFastAddBo.getNumber(), null);
            update(wxCartUpdateBo);
        }
        //还要获得此购物车信息的id
        List<MarketCart> realMarketCarts = cartMapper.selectByExample(example);
        MarketCart realMarketCart = realMarketCarts.get(0);
        //购物车信息的id
        Integer marketCartId = realMarketCart.getId();
        return marketCartId;
    }

    /**
     * 购物车付款前的检查功能
     *
     * @return
     */
    @Override
    public WxCartCheckoutVo checkout(WxCartCheckoutBo wxCartCheckoutBo) {
        //获取参数
        Integer cartId = wxCartCheckoutBo.getCartId();
        Integer addressId = wxCartCheckoutBo.getAddressId();
        //代表一条购物车信息的商品总价
        Double realPrice = 0.0;
        //根据请求参数中收货地址的id查出收货地址
        MarketAddress marketAddress = addressMapper.selectByPrimaryKey(addressId);
        //封装所有的购物车信息
        ArrayList<CartListBean> cartList = new ArrayList<>();
        //首先判断是不是来自于购物车支付
        if (cartId != 0) {
            //来自立即支付
            //根据请求参数中购物车的id查出此条购物车
            MarketCart marketCart = cartMapper.selectByPrimaryKey(cartId);
            //计算此条购物车的价格
            realPrice = realPrice(marketCart);
            //封装每一条购物车信息
            List<String> list = getStringsArray(marketCart);
            CartListBean cartListBean = getCartList(marketCart, list);
            cartList.add(cartListBean);

        } else {
            //来自购物车支付
            MarketCartExample example = new MarketCartExample();
            //获取当前用户的id
            Subject subject = SecurityUtils.getSubject();
            MarketUser principal = (MarketUser) subject.getPrincipal();
            Integer userId = principal.getId();
            //增加条件筛选
            MarketCartExample.Criteria criteria = example.createCriteria();
            //只有选择才查询
            criteria.andCheckedEqualTo(true);
            criteria.andUserIdEqualTo(userId);
            //获取购物车中选中所有商品信息
            List<MarketCart> marketCarts = cartMapper.selectByExample(example);
            //循环封装每一条购物车信息
            for (MarketCart marketCart : marketCarts) {
                //获取所有购物车信息的商品总价
                realPrice = realPrice + realPrice(marketCart);
                //封装每一条购物车信息
                List<String> list = getStringsArray(marketCart);
                CartListBean cartListBean = getCartList(marketCart, list);
                cartList.add(cartListBean);
            }
        }
        //最终统一封装返回
        WxCartCheckoutVo wxCartCheckoutVo = new WxCartCheckoutVo(0, realPrice, realPrice, cartId, -1, -1, realPrice,
                addressId, 0, 0, 0, 0, marketAddress, cartList);
        return wxCartCheckoutVo;
    }

    /**
     * 计算一条购物车信息的商品总价
     *
     * @param marketCart
     * @return
     */
    public static Double realPrice(MarketCart marketCart) {
        Double realPrice;
        Short number = marketCart.getNumber();
        BigDecimal price = marketCart.getPrice();
        String s = price.toString();
        Double dPrice = Double.valueOf(s);
        realPrice = dPrice * number;
        return realPrice;
    }
}

